# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
"""
华润保险接口
"""
import json
import logging
from urllib.parse import unquote_plus, parse_qsl
from util import post_json, random_phone, random_str, setup_logging, data2beautify


def url_decode(urlencode_str):
    """将str进行url解码为json"""
    decoded_string = unquote_plus(urlencode_str)
    query_params_list = parse_qsl(decoded_string, keep_blank_values=True)
    # 将列表转换为字典
    query_params_dict = dict(query_params_list)
    # 解析chats字段的字符串为JSON对象
    chats = json.loads(query_params_dict['chats'])
    # 解析properties字段的字符串为JSON对象
    properties = json.loads(query_params_dict['properties'])
    query_params_dict['chats'] = chats
    query_params_dict['properties'] = properties
    logging.info(f'短信回调入参解析结果：\n{data2beautify(query_params_dict)}')
    return query_params_dict


class HuaRunAPI:
    def __init__(self, ip='172.18.160.153', port='9705', token='16401387'):
        self.url_prefix = f'http://{ip}:{port}'
        self.token = token
        self.headers = {'Content-Type': 'application/json'}

    def import_phone(self, request_id: str, task_id, customers: list[dict]):
        """批量导入手机号"""
        url = f"{self.url_prefix}/yicall/huarun/api/{self.token}/hurunImportUserInfo"
        req = {
            "requestId": request_id,
            "taskId": task_id,
            "customers": customers
        }
        res = post_json(url, req, headers=self.headers)
        return res

if __name__ == '__main__':
    huarun_api = HuaRunAPI()
    total_phone_num = 1
    customer_infos = []
    for x in range(total_phone_num):
        # phone = random_phone()
        phone = "18503056080"
        customer_info = {
            "number": phone,
            "tag": "姚诚测试",
            "clientUrl": "google.com",
            "properties": {
                "username": "姚诚",
                "SayHi": "姚先生",
                "shortlink": "zhuiyi.ai"
            }
        }
        customer_infos.append(customer_info)
    t_request_id = random_str(32)
    t_task_id = "513"
    huarun_api.import_phone(t_request_id, t_task_id, customer_infos)

    # with open('./华润/通话回调.txt') as f:
    #     content = f.read()
    # url_decode(content)

